// within-ind_id mcdash_id
sort ind_id mcdash_id data_as_of

// create variable for refi
gen prepaid = (data_as_of == termination_date - 1) & termination_type_id=="1"

sort ind_id mcdash_id data_as_of
replace fm_balance = . if fm_balance >= 9e+6
replace fm_mthly_pmt = . if fm_mthly_pmt >= 1e+5 | fm_mthly_pmt == 0

foreach n of numlist 5/7 {
	by ind_id mcdash_id: gen fm_balance_change`n' = fm_balance[_n+`n'] - fm_balance if prepaid==1 & zip_code == zip_code[_n+`n'] & fm_number == fm_number[_n+`n']
}

gen anyrefi = 0
foreach x of varlist fm_balance_change* {
	replace anyrefi = 1 if `x' ~= .
}

foreach x of numlist 5 10 {
	foreach n of numlist 5/7 {
		gen plainrefi`x'pct`n' = (fm_balance_change`n'/ fm_balance) <= `x'/100
	}
	egen plainrefi`x'pct = rowtotal(plainrefi`x'pct*)
}

foreach x of numlist 5 10 {
	foreach n in 1 2 {
		gen plainrefi`x'pct`n' = plainrefi`x'pct >= `n'
		gen cashrefi`x'pct`n' = anyrefi - plainrefi`x'pct`n'
		gen nonplainrefi`x'pct`n' = prepaid - plainrefi`x'pct`n'
	}
	
}
gen nonrefi = prepaid - anyrefi
drop plainrefi*pct plainrefi*pct5 plainrefi*pct6 plainrefi*pct7


// dummy for auto loan origination
sort ind_id mcdash_id data_as_of
foreach n of numlist 1 2 {
	by ind_id mcdash_id: gen auto_balance_change`n' = auto_balance - auto_balance[_n-`n'] if _n > `n'
	replace auto_balance_change`n' = 0 if auto_balance_change`n' == .
	
	gen auto_number_change`n' = auto_number > auto_number[_n-`n'] if _n > `n'
	replace auto_number_change`n' = 0 if auto_number_change`n' == .
}

by ind_id mcdash_id: gen auto_balance_change3 = auto_balance[_n+1] - auto_balance[_n-1] if _n > 1 & _n < _N
replace auto_balance_change3 = 0 if auto_balance_change3 == .

by ind_id mcdash_id: gen auto_number_change3 = auto_number[_n+1] > auto_number[_n-1] if _n > 1 & _n < _N
replace auto_number_change3 = 0 if auto_number_change3 == .


gen auto_orig = auto_balance_change1 > 5000 & auto_balance_change2 > 5000 & auto_balance_change3 > 5000 & inlist(1, auto_number_change1, auto_number_change2, auto_number_change3)
gen auto_orig_amount = auto_balance_change1 * auto_orig

gen auto_orig3 = auto_balance_change1 > 3000 & auto_balance_change2 > 3000 & auto_balance_change3 > 3000 & inlist(1, auto_number_change1, auto_number_change2, auto_number_change3)
gen auto_orig3_amt = auto_balance_change1 * auto_orig3


by ind_id mcdash_id: gen lag_auto_balance = auto_balance[_n-1] if _n>1
by ind_id mcdash_id: gen lag_auto_balance_dum = lag_auto_balance>0 if _n>1


by ind_id mcdash_id: gen auto_orig_after = sum(auto_orig)
by ind_id mcdash_id: replace auto_orig_after = sum(auto_orig_after - auto_orig)


